package math;

public class Offer43 {
    //1 ~ n中1的个数
    /**
     * 所需迭代数字：
     * 1. 高位组成的数字high
     * 2. 低位组成的数字low
     * 3. 当前数位的数字cur
     * 4. 当前到达的数位对应的10次幂d，如个位就是10^0 = 1, 十位就是10 ^ 1 = 10
     * 
     * 遍历结束：high == 0，即高位不存在数字了
     * 结果：sum，表示1的总数
     */
   static class Solution {
        public int countDigitOne(int n) {
            int high = n / 10, low = 0, cur = n % 10, d = 1, sum = 0;
            while (high != 0) {
                if (cur == 0) {
                    sum += high * d;
                } else if (cur == 1) {
                    sum += high * d + low + 1;
                } else {
                    sum += (high + 1) * d;
                }

                //参数迭代：
                low = cur * d + low;
                d *= 10;
                cur = high % 10;
                high /= 10;
            }
            if (cur == 1) {
                sum += low + 1;
            } else if (cur > 1) {
                sum += d;
            }
            return sum;
        }

        public int countDigitOne1(int n) {
            int digit = 1, high = n / 10, cur = n % 10, low = 0;
            int count = 0;
            while (high != 0 || cur != 0) {
                if (cur == 0) count += high * digit;
                else if (cur == 1) count += high * digit + low + 1;
                else count += (high + 1) * digit;
                low += cur * digit;
                cur = high % 10;
                high /= 10;
                digit *= 10;
                
            }
    
            return count;
        }
    
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        // int res = s.countDigitOne(23010);
        int res = s.countDigitOne(23010);
        System.out.println(res);
    }
}
